//
//  CustomPageControl.swift
//  shopAssistant
//
//  Created by 周文杰 on 2016/10/31.
//  Copyright © 2016年 com.weitaming. All rights reserved.
//

import UIKit

class CustomPageControl: UIPageControl {

    let dotActiveImage = UIImage(named: "page_active_dot.png")!
    let dotInactiveImage = UIImage(named: "page_inactive_dot.png")!
    let squareActiveImage = UIImage(named: "page_active_square.png")!
    let squareInactiveImage = UIImage(named: "page_inactive_square.png")!

    var squreImage: Bool = false
    
    override var currentPage: Int {
        set {
            super.currentPage = newValue
            self.updateDots()
        }
        get {
            return super.currentPage
        }
    }
    
    override convenience init(frame: CGRect) {
        self.init(frame:frame, tailSquare:false)
    }
    
    init(frame: CGRect, tailSquare: Bool) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.clear
        self.pageIndicatorTintColor = UIColor.clear
        self.currentPageIndicatorTintColor = UIColor.clear
        self.squreImage = tailSquare
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    let kImageWidth: CGFloat = 8
    let kDotTag: Int = 1000
    
    func updateDots() {
        let count = self.subviews.count
        for i in 0..<count {
            let dot = (self.subviews)[i]
            let newDot = UIImageView(frame: CGRect(x: 0, y: 0, width: kImageWidth, height: kImageWidth))
            var dotImg: UIImage? = nil
            if i == self.currentPage {
                if i == count - 1 && squreImage {
                    dotImg = squareActiveImage
                } else {
                    dotImg = dotActiveImage
                }
            } else {
                if i == count - 1 && squreImage {
                    dotImg = squareInactiveImage
                } else {
                    dotImg = dotInactiveImage
                }
            }
            newDot.image = dotImg!
            if let oldDot = dot.viewWithTag(kDotTag) {
                oldDot.removeFromSuperview()
            }
            newDot.tag = kDotTag
            dot.addSubview(newDot)
        }
    }
}
